import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Stringzhua
 * @Date 2024/10/31 10:27
 * description:
 */
public class ReentrantLockDemo01 {
    public static void main(String[] args) throws InterruptedException {
        AddThread addThread = new AddThread();
        DecThread decThread = new DecThread();

        addThread.start();
        decThread.start();

        addThread.join();
        decThread.join();

        System.out.println(Count.count);
    }
}

class Count {
    //synchronized关键字实现锁
//    public static final Object LOCK = new Object();
    public static int count = 0;

    public static ReentrantLock lock = new ReentrantLock();
}

//递增线程
class AddThread extends Thread {
    final ReentrantLock lock = Count.lock;

    @Override
    public void run() {
//        synchronized (Count.LOCK) {
//            for (int i = 0; i < 1000; i++) {
//                Count.count += 1;
//            }
//        }

        for (int i = 0; i < 1000; i++) {
            try {
                lock.lock();
                Count.count += 1;
            } finally {
                lock.unlock();
            }
        }
    }
}

//递减线程
class DecThread extends Thread {
    final ReentrantLock lock = Count.lock;

    @Override
    public void run() {
//        synchronized (Count.LOCK) {
//            for (int i = 0; i < 1000; i++) {
//                Count.count -= 1;
//            }
//        }

        for (int i = 0; i < 1000; i++) {

            try {
                lock.lock();
                Count.count -= 1;
            } finally {
                lock.unlock();
            }
        }
    }
}
